import { ref, reactive, computed } from 'vue';
import {
  getDictList,
  getDictValueByName,
  getDictNameByValue,
  clearDictList,
  getDictListSync,
  getDictNameByValueSync,
  getDictValueByNameSync,
  type DictItem
} from '@/utils/dict';

/**
 * 字典Hook
 */
export function useDict() {
  // 字典缓存
  const dictCache = reactive<Record<string, DictItem[]>>({});

  // 加载状态
  const loading = ref(false);

  /**
   * 获取字典列表（异步）
   */
  const getDictListAsync = async (typeCode: string): Promise<DictItem[]> => {
    if (dictCache[typeCode]) {
      return dictCache[typeCode];
    }

    loading.value = true;
    try {
      const list = await getDictList(typeCode);
      dictCache[typeCode] = list;
      return list;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取字典列表（同步，从缓存）
   */
  const getDictListSyncLocal = (typeCode: string): DictItem[] => {
    return getDictListSync(typeCode);
  };


  /**
   * 根据字典名称获取字典值（异步）
   */
  const getDictValueByNameAsync = async (typeCode: string, dictName: string): Promise<string | null> => {
    return getDictValueByName(typeCode, dictName);
  };

  /**
   * 根据字典名称获取字典值（同步）
   */
  const getDictValueByNameSyncLocal = (typeCode: string, dictName: string): string | null => {
    return getDictValueByNameSync(typeCode, dictName);
  };

  /**
   * 根据字典值获取字典名称（异步）
   */
  const getDictNameByValueAsync = async (typeCode: string, dictValue: string): Promise<string | null> => {
    return getDictNameByValue(typeCode, dictValue);
  };

  /**
   * 根据字典值获取字典名称（同步）
   */
  const getDictNameByValueSyncLocal = (typeCode: string, dictValue: string): string | null => {
    return getDictNameByValueSync(typeCode, dictValue);
  };

  /**
   * 清空字典缓存
   */
  const clearDict = () => {
    clearDictList();
    Object.keys(dictCache).forEach(key => {
      delete dictCache[key];
    });
  };

  /**
   * 预加载字典
   */
  const preloadDict = async (typeCodes: string[]) => {
    const promises = typeCodes.map(typeCode => getDictListAsync(typeCode));
    await Promise.all(promises);
  };

  return {
    dictCache: computed(() => dictCache),
    loading: computed(() => loading.value),
    // 异步方法
    getDictList: getDictListAsync,
    getDictValueByName: getDictValueByNameAsync,
    getDictNameByValue: getDictNameByValueAsync,
    // 同步方法
    getDictListSync: getDictListSyncLocal,
    getDictValueByNameSync: getDictValueByNameSyncLocal,
    getDictNameByValueSync: getDictNameByValueSyncLocal,
    // 工具方法
    clearDict,
    preloadDict
  };
}

/**
 * 单个字典Hook
 */
export function useSingleDict(typeCode: string) {
  const dictList = ref<DictItem[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  /**
   * 加载字典
   */
  const loadDict = async () => {
    loading.value = true;
    error.value = null;

    try {
      const list = await getDictList(typeCode);
      dictList.value = list;
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载字典失败';
      console.error('加载字典失败:', err);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 根据值获取名称
   */
  const getNameByValue = (value: string): string | null => {
    const item = dictList.value.find(item => item.dictValue === value);
    return item ? item.dictName : null;
  };

  /**
   * 根据名称获取值
   */
  const getValueByName = (name: string): string | null => {
    const item = dictList.value.find(item => item.dictName === name);
    return item ? item.dictValue : null;
  };

  // 自动加载
  loadDict();

  return {
    dictList: computed(() => dictList.value),
    loading: computed(() => loading.value),
    error: computed(() => error.value),
    loadDict,
    getNameByValue,
    getValueByName
  };
} 